<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222" media="(prefers-color-scheme: light)">
<meta name="theme-color" content="#222" media="(prefers-color-scheme: dark)"><meta name="generator" content="Hexo 6.3.0">
<link rel="preconnect" href="https://fonts.googleapis.com" crossorigin>
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">

<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,300italic,400,400italic,700,700italic%7CZCOOL+QingKe+HuangYou:300,300italic,400,400italic,700,700italic%7CNoto+Sans+Simplified+Chinese:300,300italic,400,400italic,700,700italic%7CJetBrains+Mono:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">

<link rel="stylesheet" href="/lib/@fortawesome/fontawesome-free/css/all.min.css" integrity="sha256-HtsXJanqjKTc8vVQjO4YMhiqFoXkfBsjBWcX91T1jr8=" crossorigin="anonymous">
  <link rel="stylesheet" href="/lib/animate.css/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">
  <link rel="stylesheet" href="/lib/@fancyapps/ui/dist/fancybox/fancybox.css" integrity="sha256-RvRHGSuWAxZpXKV9lLDt2e+rZ+btzn48Wp4ueS3NZKs=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"wyatex.online","root":"/","images":"/images","scheme":"Pisces","darkmode":true,"version":"8.18.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":true,"style":"mac"},"fold":{"enable":false,"height":500},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":true,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":true}}</script><script src="/js/config.js"></script>

    <meta name="description" content="记录Dart的一些特性">
<meta property="og:type" content="article">
<meta property="og:title" content="Dart核心特性">
<meta property="og:url" content="https://wyatex.online/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/Dart%E6%A0%B8%E5%BF%83%E7%89%B9%E6%80%A7/index.html">
<meta property="og:site_name" content="Wyatex&#96;s blog">
<meta property="og:description" content="记录Dart的一些特性">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-09-20T11:01:04.000Z">
<meta property="article:modified_time" content="2023-05-05T01:25:47.045Z">
<meta property="article:author" content="Wyatex">
<meta property="article:tag" content="学习笔记">
<meta property="article:tag" content="Dart">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="https://wyatex.online/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/Dart%E6%A0%B8%E5%BF%83%E7%89%B9%E6%80%A7/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"https://wyatex.online/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/Dart%E6%A0%B8%E5%BF%83%E7%89%B9%E6%80%A7/","path":"学习笔记/Dart核心特性/","title":"Dart核心特性"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>Dart核心特性 | Wyatex`s blog</title>
  








  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">Wyatex`s blog</p>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签<span class="badge">97</span></a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类<span class="badge">26</span></a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档<span class="badge">155</span></a></li><li class="menu-item menu-item-编程"><a href="/programming/" rel="section"><i class="fa fa-book fa-fw"></i>编程</a></li><li class="menu-item menu-item-蹲坑读物"><a href="/%E5%B9%B2%E8%B4%A7/%E5%BC%80%E5%8F%91%E4%BA%A4%E6%B5%81%E7%BE%A4%E5%88%86%E4%BA%AB%E8%AE%B0%E5%BD%95/" rel="section"><i class="fa fa-book fa-fw"></i>蹲坑读物</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E6%A1%88%E4%BE%8B%E4%BB%8B%E7%BB%8D"><span class="nav-number">1.</span> <span class="nav-text">案例介绍</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E7%B1%BB%E6%8A%BD%E8%B1%A1%E6%94%B9%E9%80%A0"><span class="nav-number">2.</span> <span class="nav-text">类抽象改造</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E6%96%B9%E6%B3%95%E6%94%B9%E9%80%A0"><span class="nav-number">3.</span> <span class="nav-text">方法改造</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%AF%B9%E8%B1%A1%E5%88%9D%E5%A7%8B%E5%8C%96%E6%96%B9%E5%BC%8F%E7%9A%84%E4%BC%98%E5%8C%96"><span class="nav-number">4.</span> <span class="nav-text">对象初始化方式的优化</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Wyatex"
      src="/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">Wyatex</p>
  <div class="site-description" itemprop="description">这里是我用来做笔记的网站哟~</div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">155</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">26</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">97</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author animated">
      <span class="links-of-author-item">
        <a href="https://github.com/wyatex" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;wyatex" rel="noopener me" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:wyatex@qq.com" title="E-Mail → mailto:wyatex@qq.com" rel="noopener me" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>

        </div>
      </div>
    </div>

    
    <div class="sidebar-inner sidebar-blogroll">
      <div class="links-of-blogroll animated">
        <div class="links-of-blogroll-title"><i class="fa fa-globe fa-fw"></i>
          链接
        </div>
        <ul class="links-of-blogroll-list">
            <li class="links-of-blogroll-item">
              <a href="https://antfu.me/" title="https:&#x2F;&#x2F;antfu.me&#x2F;" rel="noopener" target="_blank">Anthony Fu</a>
            </li>
            <li class="links-of-blogroll-item">
              <a href="https://www.codesky.me/" title="https:&#x2F;&#x2F;www.codesky.me&#x2F;" rel="noopener" target="_blank">CodeSky</a>
            </li>
            <li class="links-of-blogroll-item">
              <a href="https://learn.lianglianglee.com/" title="https:&#x2F;&#x2F;learn.lianglianglee.com&#x2F;" rel="noopener" target="_blank">技术文章摘抄</a>
            </li>
        </ul>
      </div>
    </div>
        <div class="pjax">
        </div>
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://wyatex.online/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/Dart%E6%A0%B8%E5%BF%83%E7%89%B9%E6%80%A7/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpg">
      <meta itemprop="name" content="Wyatex">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Wyatex`s blog">
      <meta itemprop="description" content="这里是我用来做笔记的网站哟~">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="Dart核心特性 | Wyatex`s blog">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Dart核心特性
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2020-09-20 19:01:04" itemprop="dateCreated datePublished" datetime="2020-09-20T19:01:04+08:00">2020-09-20</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">更新于</span>
      <time title="修改时间：2023-05-05 09:25:47" itemprop="dateModified" datetime="2023-05-05T09:25:47+08:00">2023-05-05</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/" itemprop="url" rel="index"><span itemprop="name">学习笔记</span></a>
        </span>
    </span>

  
    <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv">
      <span class="post-meta-item-icon">
        <i class="far fa-eye"></i>
      </span>
      <span class="post-meta-item-text">阅读次数：</span>
      <span id="busuanzi_value_page_pv"></span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody"><p>记录Dart的一些特性</p>
<span id="more"></span>

<h1 id="案例介绍"><a href="#案例介绍" class="headerlink" title="案例介绍"></a>案例介绍</h1><p>这里选择的是一段购物车程序，先不使用Dart独有的特性，然后逐步加入Dart语言特性。</p>
<p>首先在不使用任何Dart语法特性的情况下，一个有着基本功能的购物车程序如下：</p>
<figure class="highlight dart"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 定义商品 Item 类</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Item</span> </span>&#123;</span><br><span class="line">  <span class="built_in">double</span> price;</span><br><span class="line">  <span class="built_in">String</span> name;</span><br><span class="line">  Item(name, price) &#123;</span><br><span class="line">    <span class="keyword">this</span>.name = name;</span><br><span class="line">    <span class="keyword">this</span>.price = price;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line"><span class="comment">// 定义购物车类</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ShoppingCart</span> </span>&#123;</span><br><span class="line">  <span class="built_in">String</span> name;</span><br><span class="line">  <span class="built_in">DateTime</span> date;</span><br><span class="line">  <span class="built_in">String</span> code;</span><br><span class="line">  <span class="built_in">List</span>&lt;Item&gt; bookings;</span><br><span class="line"> </span><br><span class="line">  price() &#123;</span><br><span class="line">    <span class="built_in">double</span> sum = <span class="number">0.0</span>;</span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">var</span> i <span class="keyword">in</span> bookings) &#123;</span><br><span class="line">      sum += i.price;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> sum;</span><br><span class="line">  &#125;</span><br><span class="line"> </span><br><span class="line">  ShoppingCart(name, code) &#123;</span><br><span class="line">    <span class="keyword">this</span>.name = name;</span><br><span class="line">    <span class="keyword">this</span>.code = code;</span><br><span class="line">    <span class="keyword">this</span>.date = <span class="built_in">DateTime</span>.now();</span><br><span class="line">  &#125;</span><br><span class="line"> </span><br><span class="line">  getInfo() &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="string">&#x27;购物车信息:&#x27;</span> +</span><br><span class="line">          <span class="string">&#x27;\n-----------------------------&#x27;</span> +</span><br><span class="line">          <span class="string">&#x27;\n 用户名: &#x27;</span> + name+ </span><br><span class="line">          <span class="string">&#x27;\n 优惠码: &#x27;</span> + code + </span><br><span class="line">          <span class="string">&#x27;\n 总价: &#x27;</span> + price().toString() +</span><br><span class="line">          <span class="string">&#x27;\n 日期: &#x27;</span> + date.toString() +</span><br><span class="line">          <span class="string">&#x27;\n-----------------------------&#x27;</span>;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line"><span class="keyword">void</span> main() &#123;</span><br><span class="line">  ShoppingCart sc = ShoppingCart(<span class="string">&#x27;张三&#x27;</span>, <span class="string">&#x27;123456&#x27;</span>);</span><br><span class="line">  sc.bookings = [Item(<span class="string">&#x27;苹果&#x27;</span>,<span class="number">10.0</span>), Item(<span class="string">&#x27;鸭梨&#x27;</span>,<span class="number">20.0</span>)];</span><br><span class="line">  <span class="built_in">print</span>(sc.getInfo());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这段代码看上去和Java或者JS都没有太大的差异，接下来从表达信息入手，优化这段代码</p>
<h1 id="类抽象改造"><a href="#类抽象改造" class="headerlink" title="类抽象改造"></a>类抽象改造</h1><p>在Item类和ShoppingCart类的构造函数中，他们都只是将main函数传入的参数进行属性赋值。</p>
<p>在Dart中使用语法糖和初始化列表进行简化：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Item</span> &#123;</span><br><span class="line">  double price;</span><br><span class="line">  <span class="title class_">String</span> name;</span><br><span class="line">  <span class="title class_">Item</span>(<span class="variable language_">this</span>.<span class="property">name</span>, <span class="variable language_">this</span>.<span class="property">price</span>);</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line"><span class="keyword">class</span> <span class="title class_">ShoppingCart</span> &#123;</span><br><span class="line">  <span class="title class_">String</span> name;</span><br><span class="line">  <span class="title class_">DateTime</span> date;</span><br><span class="line">  <span class="title class_">String</span> code;</span><br><span class="line">  <span class="title class_">List</span>&lt;<span class="title class_">Item</span>&gt; bookings;</span><br><span class="line">  <span class="title function_">price</span>(<span class="params"></span>) &#123;...&#125;</span><br><span class="line">  <span class="comment">// 删掉了构造函数函数体</span></span><br><span class="line">  <span class="title class_">ShoppingCart</span>(<span class="variable language_">this</span>.<span class="property">name</span>, <span class="variable language_">this</span>.<span class="property">code</span>) : date = <span class="title class_">DateTime</span>.<span class="title function_">now</span>();</span><br><span class="line">...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>然后我们发现：Item类和ShoppingCart类中都有一个name属性，都有一个price属性&#x2F;方法，既然他们的类型和名称都一样，那么可以抽象出一个Meta基类，用于存放这两个属性。</p>
<p>因为在ShoppingCart中price只是用于计算购物车中商品的价格，那么继承Meta类后需要改写price属性的get方法：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Meta</span> &#123;</span><br><span class="line">  double price;</span><br><span class="line">  <span class="title class_">String</span> name;</span><br><span class="line">  <span class="title class_">Meta</span>(<span class="variable language_">this</span>.<span class="property">name</span>, <span class="variable language_">this</span>.<span class="property">price</span>);</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Item</span> <span class="keyword">extends</span> <span class="title class_ inherited__">Meta</span>&#123;</span><br><span class="line">  <span class="title class_">Item</span>(name, price) : <span class="variable language_">super</span>(name, price);</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line"><span class="keyword">class</span> <span class="title class_">ShoppingCart</span> <span class="keyword">extends</span> <span class="title class_ inherited__">Meta</span>&#123;</span><br><span class="line">  <span class="title class_">DateTime</span> date;</span><br><span class="line">  <span class="title class_">String</span> code;</span><br><span class="line">  <span class="title class_">List</span>&lt;<span class="title class_">Item</span>&gt; bookings;</span><br><span class="line">  </span><br><span class="line">  double get price &#123;...&#125;</span><br><span class="line">  <span class="title class_">ShoppingCart</span>(name, <span class="variable language_">this</span>.<span class="property">code</span>) : date = <span class="title class_">DateTime</span>.<span class="title function_">now</span>(),<span class="variable language_">super</span>(name,<span class="number">0</span>);</span><br><span class="line">  <span class="title function_">getInfo</span>(<span class="params"></span>) &#123;...&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>不过ShoppingCart类中的price属性的get方法和打印购物车基本信息的getinfo方法都显得冗长，接下来改进一下这两个方法。</p>
<h1 id="方法改造"><a href="#方法改造" class="headerlink" title="方法改造"></a>方法改造</h1><p>我们需要重载Item类的“+”运算符，并通过对列表对象进行归纳合并操作即可</p>
<figure class="highlight dart"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Item</span> <span class="keyword">extends</span> <span class="title">Meta</span></span>&#123;</span><br><span class="line">  ...</span><br><span class="line">  <span class="comment">// 重载了 + 运算符，合并商品为套餐商品</span></span><br><span class="line">  Item <span class="keyword">operator</span>+(Item item) =&gt; Item(name + item.name, price + item.price); </span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ShoppingCart</span> <span class="keyword">extends</span> <span class="title">Meta</span></span>&#123;</span><br><span class="line">  ...</span><br><span class="line">  <span class="comment">// 把迭代求和改写为归纳合并</span></span><br><span class="line">  <span class="built_in">double</span> <span class="keyword">get</span> price =&gt; bookings.reduce((value, element) =&gt; value + element).price;</span><br><span class="line">  ...</span><br><span class="line">  getInfo() &#123;...&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>顺便修改getInfo方法，因为字符串拼接实在是太不美观了。</p>
<figure class="highlight dart"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">getInfo () =&gt; <span class="string">&#x27;&#x27;&#x27;</span></span><br><span class="line"><span class="string">购物车信息:</span></span><br><span class="line"><span class="string">-----------------------------</span></span><br><span class="line"><span class="string">  用户名: <span class="subst">$name</span></span></span><br><span class="line"><span class="string">  优惠码: <span class="subst">$code</span></span></span><br><span class="line"><span class="string">  总价: <span class="subst">$price</span></span></span><br><span class="line"><span class="string">  Date: <span class="subst">$date</span></span></span><br><span class="line"><span class="string">-----------------------------</span></span><br><span class="line"><span class="string">&#x27;&#x27;&#x27;</span>;</span><br></pre></td></tr></table></figure>

<h1 id="对象初始化方式的优化"><a href="#对象初始化方式的优化" class="headerlink" title="对象初始化方式的优化"></a>对象初始化方式的优化</h1><p>因为有可能用户没有优惠券，所以我们需要对构造函数进行改进</p>
<figure class="highlight dart"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ShoppingCart</span> <span class="keyword">extends</span> <span class="title">Meta</span></span>&#123;</span><br><span class="line">  ...</span><br><span class="line">  <span class="comment">// 默认初始化方法，转发到 withCode 里</span></span><br><span class="line">  ShoppingCart(&#123;name&#125;) : <span class="keyword">this</span>.withCode(name:name, code:<span class="keyword">null</span>);</span><br><span class="line">  <span class="comment">//withCode 初始化方法，使用语法糖和初始化列表进行赋值，并调用父类初始化方法</span></span><br><span class="line">  ShoppingCart.withCode(&#123;name, <span class="keyword">this</span>.code&#125;) : date = <span class="built_in">DateTime</span>.now(), <span class="keyword">super</span>(name,<span class="number">0</span>);</span><br><span class="line"> </span><br><span class="line">  <span class="comment">//?? 运算符表示为 code 不为 null，则用原值，否则使用默认值 &quot; 没有 &quot;</span></span><br><span class="line">  getInfo () =&gt; <span class="string">&#x27;&#x27;&#x27;</span></span><br><span class="line"><span class="string">购物车信息:</span></span><br><span class="line"><span class="string">-----------------------------</span></span><br><span class="line"><span class="string">  用户名: <span class="subst">$name</span></span></span><br><span class="line"><span class="string">  优惠码: <span class="subst">$&#123;code??<span class="string">&quot; 没有 &quot;</span>&#125;</span></span></span><br><span class="line"><span class="string">  总价: <span class="subst">$price</span></span></span><br><span class="line"><span class="string">  Date: <span class="subst">$date</span></span></span><br><span class="line"><span class="string">-----------------------------</span></span><br><span class="line"><span class="string">&#x27;&#x27;&#x27;</span>;</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line"><span class="keyword">void</span> main() &#123;</span><br><span class="line">  ShoppingCart sc = ShoppingCart.withCode(name:<span class="string">&#x27;张三&#x27;</span>, code:<span class="string">&#x27;123456&#x27;</span>);</span><br><span class="line">  sc.bookings = [Item(<span class="string">&#x27;苹果&#x27;</span>,<span class="number">10.0</span>), Item(<span class="string">&#x27;鸭梨&#x27;</span>,<span class="number">20.0</span>)];</span><br><span class="line">  <span class="built_in">print</span>(sc.getInfo());</span><br><span class="line"> </span><br><span class="line">  ShoppingCart sc2 = ShoppingCart(name:<span class="string">&#x27;李四&#x27;</span>);</span><br><span class="line">  sc2.bookings = [Item(<span class="string">&#x27;香蕉&#x27;</span>,<span class="number">15.0</span>), Item(<span class="string">&#x27;西瓜&#x27;</span>,<span class="number">40.0</span>)];</span><br><span class="line">  <span class="built_in">print</span>(sc2.getInfo());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>因为打印这个行为非常通用，可能后面需要打印Item，所以我们需要把打印信息单独封装成一个类：PrintHelper。因为ShoppingCart 类本身已经继承自 Meta 类，考虑到 Dart 并不支持多继承，所以我们使用混合（Mixin）</p>
<figure class="highlight dart"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">abstract</span> <span class="class"><span class="keyword">class</span> <span class="title">PrintHelper</span> </span>&#123;</span><br><span class="line">  printInfo() =&gt; <span class="built_in">print</span>(getInfo());</span><br><span class="line">  getInfo();</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ShoppingCart</span> <span class="keyword">extends</span> <span class="title">Meta</span> <span class="title">with</span> <span class="title">PrintHelper</span></span>&#123;</span><br><span class="line">...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>最后在main里面使用级联操作符，这样就不需要创建临时变量了，下面是完整代码</p>
<figure class="highlight dart"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Meta</span> </span>&#123;</span><br><span class="line">  <span class="built_in">double</span> price;</span><br><span class="line">  <span class="built_in">String</span> name;</span><br><span class="line">  <span class="comment">// 成员变量初始化语法糖</span></span><br><span class="line">  Meta(<span class="keyword">this</span>.name, <span class="keyword">this</span>.price);</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Item</span> <span class="keyword">extends</span> <span class="title">Meta</span></span>&#123;</span><br><span class="line">  Item(name, price) : <span class="keyword">super</span>(name, price);</span><br><span class="line">  <span class="comment">// 重载 + 运算符，将商品对象合并为套餐商品</span></span><br><span class="line">  Item <span class="keyword">operator</span>+(Item item) =&gt; Item(name + item.name, price + item.price); </span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line"><span class="keyword">abstract</span> <span class="class"><span class="keyword">class</span> <span class="title">PrintHelper</span> </span>&#123;</span><br><span class="line">  printInfo() =&gt; <span class="built_in">print</span>(getInfo());</span><br><span class="line">  getInfo();</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line"><span class="comment">//with 表示以非继承的方式复用了另一个类的成员变量及函数</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ShoppingCart</span> <span class="keyword">extends</span> <span class="title">Meta</span> <span class="title">with</span> <span class="title">PrintHelper</span></span>&#123;</span><br><span class="line">  <span class="built_in">DateTime</span> date;</span><br><span class="line">  <span class="built_in">String</span> code;</span><br><span class="line">  <span class="built_in">List</span>&lt;Item&gt; bookings;</span><br><span class="line">  <span class="comment">// 以归纳合并方式求和</span></span><br><span class="line">  <span class="built_in">double</span> <span class="keyword">get</span> price =&gt; bookings.reduce((value, element) =&gt; value + element).price;</span><br><span class="line">  <span class="comment">// 默认初始化函数，转发至 withCode 函数</span></span><br><span class="line">  ShoppingCart(&#123;name&#125;) : <span class="keyword">this</span>.withCode(name:name, code:<span class="keyword">null</span>);</span><br><span class="line">  <span class="comment">//withCode 初始化方法，使用语法糖和初始化列表进行赋值，并调用父类初始化方法</span></span><br><span class="line">  ShoppingCart.withCode(&#123;name, <span class="keyword">this</span>.code&#125;) : date = <span class="built_in">DateTime</span>.now(), <span class="keyword">super</span>(name,<span class="number">0</span>);</span><br><span class="line"> </span><br><span class="line">  <span class="comment">//?? 运算符表示为 code 不为 null，则用原值，否则使用默认值 &quot; 没有 &quot;</span></span><br><span class="line">  <span class="meta">@override</span></span><br><span class="line">  getInfo() =&gt; <span class="string">&#x27;&#x27;&#x27;</span></span><br><span class="line"><span class="string">购物车信息:</span></span><br><span class="line"><span class="string">-----------------------------</span></span><br><span class="line"><span class="string">  用户名: <span class="subst">$name</span></span></span><br><span class="line"><span class="string">  优惠码: <span class="subst">$&#123;code??<span class="string">&quot; 没有 &quot;</span>&#125;</span></span></span><br><span class="line"><span class="string">  总价: <span class="subst">$price</span></span></span><br><span class="line"><span class="string">  Date: <span class="subst">$date</span></span></span><br><span class="line"><span class="string">-----------------------------</span></span><br><span class="line"><span class="string">&#x27;&#x27;&#x27;</span>;</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line"><span class="keyword">void</span> main() &#123;</span><br><span class="line">  ShoppingCart.withCode(name:<span class="string">&#x27;张三&#x27;</span>, code:<span class="string">&#x27;123456&#x27;</span>)</span><br><span class="line">  ..bookings = [Item(<span class="string">&#x27;苹果&#x27;</span>,<span class="number">10.0</span>), Item(<span class="string">&#x27;鸭梨&#x27;</span>,<span class="number">20.0</span>)]</span><br><span class="line">  ..printInfo();</span><br><span class="line"> </span><br><span class="line">  ShoppingCart(name:<span class="string">&#x27;李四&#x27;</span>)</span><br><span class="line">  ..bookings = [Item(<span class="string">&#x27;香蕉&#x27;</span>,<span class="number">15.0</span>), Item(<span class="string">&#x27;西瓜&#x27;</span>,<span class="number">40.0</span>)]</span><br><span class="line">  ..printInfo();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
    </div>

    
    
    

    <footer class="post-footer">
          

<div class="post-copyright">
<ul>
  <li class="post-copyright-author">
      <strong>本文作者： </strong>Wyatex
  </li>
  <li class="post-copyright-link">
      <strong>本文链接：</strong>
      <a href="https://wyatex.online/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/Dart%E6%A0%B8%E5%BF%83%E7%89%B9%E6%80%A7/" title="Dart核心特性">https://wyatex.online/学习笔记/Dart核心特性/</a>
  </li>
  <li class="post-copyright-license">
      <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>

          <div class="post-tags">
              <a href="/tags/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/" rel="tag"># 学习笔记</a>
              <a href="/tags/Dart/" rel="tag"># Dart</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/%E9%87%8D%E5%AD%A6%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F%E7%AC%94%E8%AE%B0-1/" rel="prev" title="重学操作系统笔记-1">
                  <i class="fa fa-angle-left"></i> 重学操作系统笔记-1
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/%E5%89%8D%E7%AB%AF/js%E5%85%83%E7%BC%96%E7%A8%8B%EF%BC%9A%E4%BB%A3%E7%90%86/" rel="next" title="js元编程笔记：代理">
                  js元编程笔记：代理 <i class="fa fa-angle-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">

  <div class="copyright">
    &copy; 2019 – 
    <span itemprop="copyrightYear">2024</span>
    <span class="with-love">
      <i class="fa fa-heart"></i>
    </span>
    <span class="author" itemprop="copyrightHolder">Wyatex</span>
  </div>
<div class="busuanzi-count">
    <span class="post-meta-item" id="busuanzi_container_site_uv">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-item" id="busuanzi_container_site_pv">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>

    </div>
  </footer>

  
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script size="300" alpha="0.6" zIndex="-1" src="/lib/ribbon.js/dist/ribbon.min.js"></script>
  <script src="/lib/animejs/lib/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
  <script src="/lib/@next-theme/pjax/pjax.min.js" integrity="sha256-vxLn1tSKWD4dqbMRyv940UYw4sXgMtYcK6reefzZrao=" crossorigin="anonymous"></script>
  <script src="/lib/@fancyapps/ui/dist/fancybox/fancybox.umd.js" integrity="sha256-q8XkJ6dj5VwSvzI8+nATCHHQG+Xv/dAZBCgqmu93zOY=" crossorigin="anonymous"></script>
  <script src="/lib/lozad/dist/lozad.min.js" integrity="sha256-mOFREFhqmHeQbXpK2lp4nA3qooVgACfh88fpJftLBbc=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script><script src="/js/pjax.js"></script>

  <script src="/lib/hexo-generator-searchdb/dist/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>




  <script src="/js/third-party/fancybox.js"></script>



  
  <script data-pjax async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>





</body>
</html>
